/*
 * @Date: 2022-03-28 16:05:51
 * @LastEditors: 春贰
 * @gitee: https://gitee.com/chun22222222
 * @github: https://github.com/chun222
 * @Desc:
 * @LastEditTime: 2022-06-15 15:56:42
 * @FilePath: \server\system\service\SysConfigService\sysconfigservice.go
 */
package SysConfigService

import (
	"errors"

	"go2admin_pure/system/core/db"
	"go2admin_pure/system/core/request"
	"go2admin_pure/system/model/CommonModel"
	"go2admin_pure/system/model/DbModel"
	"go2admin_pure/system/model/RequestModel"
	"go2admin_pure/system/util/str"
)

type SysConfigService struct{}

//新增
func (SysConfigService *SysConfigService) Add(info *DbModel.SysConfig) (err error) {
	result := db.Instance().Create(info)
	return result.Error
}

//修改
func (SysConfigService *SysConfigService) Edit(info *DbModel.SysConfig) (err error) {
	var data DbModel.SysConfig
	if err := db.Instance().Where("name = ?", info.Name).First(&data).Error; err != nil {
		return err
	}
	//忽略字段
	return db.Instance().Omit("CreatedAt").Save(info).Error
}

//分页列表
func (SysConfigService *SysConfigService) List(info RequestModel.SysConfig) (err error, list interface{}, total int64) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)

	db := db.Instance().Model(&DbModel.SysConfig{})
	//动态查询条件
	request.GenWhere(info, db)
	var dataList []DbModel.SysConfig
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	err = db.Limit(limit).Offset(offset).Find(&dataList).Error
	return err, dataList, total
}

//所有配置返回给前端
func (SysConfigService *SysConfigService) AllConfig() (error, string) {
	db := db.Instance().Model(&DbModel.SysConfig{})
	var dataList []DbModel.SysConfig

	err := db.Find(&dataList).Error
	if err != nil {
		return err, "{}"
	} else {
		result := "{"
		for i, v := range dataList {
			if i == len(dataList)-1 {
				result += "\"" + v.Name + "\":" + v.ValueString
			} else {
				result += "\"" + v.Name + "\":" + v.ValueString + ","
			}
		}
		result += "}"

		return nil, result
	}
}

//读取指定配置
func (SysConfigService *SysConfigService) ConfigDic(name string) (error, string) {
	db := db.Instance().Model(&DbModel.SysConfig{})
	var dataList DbModel.SysConfig

	err := db.Where("name = ?", name).First(&dataList).Error
	if err != nil {
		return err, ""
	} else {
		return nil, dataList.ValueString
	}

}

//删除
func (SysConfigService *SysConfigService) Remove(info CommonModel.Names) (err error) {
	for _, v := range info.Names {
		if str.StartsWith(v, "sys_") {
			return errors.New("can not delete system config")
		}
	}
	result := db.Instance().Delete(&DbModel.SysConfig{}, info.Names)
	return result.Error
}
